#!/bin/bash
#========================================================================
# Author: YSLin
# Email: 
# File Name: processLoop.sh
# Description: 
#   The Init function is responsible for stopping
#   any running instances of the program and then starting it again. 
#
#   The CleanUp function is responsible for killing the running program and then exiting.
# Edit History: 
#   2011-01-21    File created.
#========================================================================
if [ $# -lt 1 ] ; then
	echo "USAGE: `basename $0` command."
	exit 0
fi
Init() {
	printf "INFO: Initializing... "
	# check if the last backgrounded pid is valid, if it is
	# try an kill it.
	kill -0 $! 2> /dev/null;
	if [ $? -eq 0 ] ; then
		kill $! > /dev/null 2>&1
		if [ $? -ne 0 ] ; then
			echo "ERROR: Already running as pid $!. Exiting."
			exit 1
		fi
	fi
	# start a new program in the background
	$PROG &
	printf "Done.\n"
}
CleanUp() {
	echo "CleanUp";
	kill -9 $! ; exit 2 ;
}
# main()
trap CleanUp 2 3 15
trap Init 1
PROG=$1
Init
while : ;
do
	wait $!
	$PROG &
done
